import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getBooks, SGaddBook, SGremoveBook, SGisExistsDirname, selectVersion, SGgetUploadToken } from '../../actions/books.action';
import { getTypes } from '../../actions/types.action';
import Layer from '../../components/SimpleLayer/Layer';
import Message from '../../components/SimpleLayer/Message';
import SelectNavHOC from '../SelectNavHOC';
import ContentSlideIn from '../ContentSlideIn';
import SlideInTr from '../SlideInTr';
import base64 from 'base-64';
import {filterTag,winSize,clearTag,$$} from '../../modules/utils';

function recombineBooks(books, v){
	let bks = [...books];
	let def = 
	bks = bks&&bks.map(bk => {
		if (bk.isMdpage==='1' && bk.books) {
			// add selected
			return {
				versions: bk.versions, 
				parentId: bk.parentId, 
				...(bk.books.filter(k => k.selected)[0] || bk.books.filter(k => bk.versions[0] === k.version)[0]), 
				index: bk.index, 
				dirname: bk.dirname
			};
		}
		return bk;
	});
	return bks;
}
function copyUrl2(){
	var Url2=document.getElementById("biao1");
	Url2.select(); 
	document.execCommand("Copy");
}

@SelectNavHOC
@connect(mapStateToProps,mapDispatchToProps)
export default class Books extends Component {
	xhr=null
	posting=false
	componentDidMount(){
		let {user,BooksList,TypesList,selectNav} = this.props;
		BooksList({
			token:user.token,
			userId:user.id
		});
		TypesList({
			token:user.token
		});
		selectNav('bm');
	}
	showErr(content){
		Message.error({
			top:'6px',
			width:'300',
			content,
			delayAutoClose:1200,
			yes:false
		});
	}
	confirm(str,fn){
		let $this=this;
		Layer({
			width:350,
			height:200,
			content:'<div style="line-height: 80px;font-size: 14px;color: #666;text-align: center;">'+str+'</div>',
			onOK(){
				fn&&fn();
				setTimeout(()=>{this.delete()},200);
			}
		});
	}
	showLayer(id,book){
		let {
			types,
			books
		} = this.props;
		books = recombineBooks(books);
		let options = types.map((tp,i)=>{
			return `<div class="dpitem nobr ease3" data-value="${tp.id}" data-name="${tp.name}"><i class="iconfont icon-check"></i>${tp.name}</div>`
		}).join('');
		let thisbook = books.filter(bk=>bk.id===id)[0];
		let $this=this;
		
		let bkInfo=document.createElement('div');
		bkInfo.className='book-info-templ';
		bkInfo.style.display='none';
		if(document.querySelector('.book-info-templ')) document.body.removeChild(document.querySelector('.book-info-templ'));
		document.body.appendChild(bkInfo);
		let uploadedInfo=function(e){
			let uploadedbook=document.getElementById('upload').getAttribute('data-book');
			let bookinfo=document.querySelector('.book-info-templ');
			if(uploadedbook){
				let info='附件中配置信息有误！';
				try {
					uploadedbook=JSON.parse(decodeURIComponent(base64.decode(uploadedbook)));
				} catch (error) {
					console.log(error);
					uploadedbook={};
				}
				
				if(Object.keys(uploadedbook).length){
					info='';
					for(let item in uploadedbook){
						info+=item+' : '+filterTag(uploadedbook[item])+'<br>';
					}
				}
				if(bookinfo.style.display==='none'){
					bookinfo.style.display='block';
				}
				bookinfo.innerHTML=	info;
				var rect=e.target.getBoundingClientRect();
				bookinfo.style.left=(rect.left+85)+'px';
				bookinfo.style.top=(rect.top-8)+'px';
			}
		}

		Layer({
			width:450,
			height:490,
			alwaysCenter:true,
			title:`${id?'修改':'新增'}电子书`,
			content:`
				<div class="genbook">
					<div class="atr"><span class="origin">${[window.location.protocol,'//',window.location.host,'/'].join('')}</span><span class="red">*</span>路<span style="visibility:hidden">啊</span>径：&nbsp;&nbsp;<input type="text" maxlength=30 data-value="0" class="dirname inpt ease3" value="${id?thisbook.dirname:''}" /></div>
					<div class="atr"><span class="red">*</span>书<span style="visibility:hidden">啊</span>名：&nbsp;&nbsp;<input type="text" maxlength=15 class="name inpt ease3" value="${id?thisbook.name:''}" /></div>
					<div class="atr"><span class="red">*</span>作<span style="visibility:hidden">啊</span>者：&nbsp;&nbsp;<input type="text" maxlength=15 class="author inpt ease3" value="${id?thisbook.author:''}" /></div>
					<div class="atr"><span class="red">*</span>分<span style="visibility:hidden">啊</span>类：&nbsp;&nbsp;<div class="dropdown dib" style="width: 261px;"><div data-value="${id?thisbook.typesId:(types[0]?types[0].id:-1)}" class="dptitle nobr">${id?thisbook.typesName:(types[0]?types[0].name:'请选择')}</div><i class="fr iconfont arrow icon-down"></i><div class="dplist">${options}</div></div></div>
					<div class="atr"><span class="red">*</span>描<span style="visibility:hidden">啊</span>述：&nbsp;&nbsp;<textarea maxlength=85 class="desc inpt ease3" >${id?thisbook.desc:''}</textarea></div>
					<div class="atr" style="margin-top: 23px;position:relative;">
						<div class="iconfont icon-yes"></div><label for="upload" class="progress" style="display:none;"><span class="filename nobr"></span><div class="progressbar ease3"></div></label><span class="red">*</span>电子书：&nbsp;&nbsp;<label class="ease3 labfile" for="upload">上传附件</label><a href="/bookJson.html" target="_blank" class="iconfont icon-wenhao filetype-info ease3"></a><input type="file" id="upload" class="pswd1 inpt " data-uploading="${id?'0':''}" data-index="${id?thisbook.index:''}" data-md="${id?thisbook.isMdpage:'-1'}" data-book="${id?filterTag((thisbook.bookjson)):''}" /></div>
					<div class="atr useconf">使用配置信息</div><a href="/bookJson.html" target="_blank" class="atr iconfont icon-wenhao filetype-info1 ease3" style="display:none;margin-top: 0;"></a>
				</div>	
			`,
			onShow(){
				clearTag();
				let upload=document.querySelector('#upload');
				upload.onchange = (e)=> {
					if ($this.xhr) {
						$this.xhr.abort();
					}
					var params = book?{vs:book.versions?book.versions.join(','):'',v:book.version}:null;
					if(e.target.files.length) $this.upload(params);
				}
				var dirname=document.querySelector('.dirname');
				var dropdown=document.querySelector('.dropdown');
				var dplist=document.querySelector('.dplist');
				var useconf=document.querySelector('.useconf');
				var tip=document.querySelector('.filetype-info');
				var tip1=document.querySelector('.filetype-info1');
				var reg=/[^$&\[\].-\w]+/;

				dirname.style.paddingLeft=(document.querySelector('.origin').offsetWidth+9)+'px';
				dirname.onkeyup=dirname.onblur=function(){
					
					if (reg.test(this.value)) {
						this.value=this.value.replace(reg,'');
					}
					this.setAttribute('data-value',0);
				}
				dirname.onblur=function(){
					$this.props.IsExistsDirname({dirname:dirname.value,id:id||''});
					// this.setAtrribute('data-value',0);
				}
				dplist.onmouseleave=function(){
					dropdown.className='dropdown dib';
				}
				dropdown.onclick=function(){
					var title=document.querySelector('.dptitle');
					var act=this.className.indexOf('dropdownin')===-1;
					if (act) {
						[...dropdown.querySelectorAll('.dpitem')].forEach(item=>{
							if (title.getAttribute('data-value').split(',').indexOf(item.getAttribute('data-value'))!==-1) {
								item.className+=' dpitemed';
							}
						});
					}
					this.className='dropdown dib '+(act?'dropdownin':'');
				}
				var dpitem=[...dropdown.querySelectorAll('.dpitem')];
				dpitem.forEach(item=>{
					item.onclick=function(e){
						e.stopPropagation();
						var act=this.className.indexOf('dpitemed')===-1;
						var title=document.querySelector('.dptitle');
						this.className='dpitem nobr ease3 '+(act?'dpitemed':'');
						var cks=[...dropdown.querySelectorAll('.dpitemed')].map(ck=>({id:ck.getAttribute('data-value'),name:ck.getAttribute('data-name')}));	
						title.innerHTML=cks.map(ck=>ck.name).join(',');
						title.setAttribute('data-value',cks.map(ck=>ck.id).join(','));
					}
				});
				useconf.onmouseover=function(e){
					uploadedInfo(e);	
				}
				
				useconf.onmouseout=function(e){//=tip.onmouseout=tip1.onmouseout
					document.querySelector('.book-info-templ').style.display='none';
				}
				useconf.onclick=function(){
					try{
						let book=JSON.parse(decodeURIComponent(base64.decode(document.querySelector('#upload').getAttribute('data-book'))));
						var dirname=document.querySelector('.dirname');
						var name=document.querySelector('.name');
						var author=document.querySelector('.author');
						var desc=document.querySelector('.desc');
						if (book.dirname) {
							dirname.value=filterTag(book.pathname.replace(reg,''));
						}
						if (book.name) {
							name.value=filterTag(book.name);
						}
						if (book.description) {
							desc.value=filterTag(book.description);
						}
						if (book.author) {
							author.value=filterTag(book.author);
						}
					}catch(e){}
				}
			},
			onOK(){
				if ($this.posting) {
					$this.showErr('数据处理中...');
					return;
				}
				var dirname=document.querySelector('.dirname');
				var name=document.querySelector('.name');
				var author=document.querySelector('.author');
				var dptitle=document.querySelector('.dptitle');
				var desc=document.querySelector('.desc');
				var upload=document.querySelector('#upload');
				
				if (!dirname.getAttribute('data-value')==='1') {
					$this.showErr('路径已存在！');
					return;
				}
				if (!dirname.value) {
					dirname.focus();
					return;
				}
				if (!name.value) {
					name.focus();
					return;
				}
				if (!author.value) {
					author.focus();
					return;
				}
				var titleV=dptitle.getAttribute('data-value');
				if(!titleV||titleV==='-1'){
					$this.showErr('请选择分类或添加分类！');
					return;
				}
				if (!desc.value) {
					desc.focus();
					return;
				}
				var isUploading=upload.getAttribute('data-uploading');
				var errRes=upload.getAttribute('data-res');
				if (isUploading==='1') {
					$this.showErr('正在上传附件...');
					return;
				}
				if (isUploading!=='0'){
					$this.showErr('请上传附件！');
					return;
				} 
				if (errRes) {
					$this.showErr(errRes);
					return;
				}
				$this.posting=true;
				let _book={
					logo:id?thisbook.logo:''
				}
				try{
					_book=JSON.parse(decodeURIComponent(base64.decode(upload.getAttribute('data-book'))));
					if(_book.logo) {
						_book.logo=_book.logo.replace(/[/\\]+.+?[/\\]+/,'/'+dirname.value+'/')
					}
				}catch(e){}
				let subbook=()=>{
					$this.props.AddBook({
						parentId:thisbook&&thisbook.parentId||'',
						id:id?id:'',
						dirname:dirname.value,
						name:name.value,
						desc:desc.value,
						author:author.value,
						userId:$this.props.user.id,
						typesId:dptitle.getAttribute('data-value'),
						typesName:dptitle.innerHTML,
						logo:_book.logo,
						bookjson:base64.encode(encodeURIComponent(JSON.stringify(_book))),
						bookDir:_book.bookDir||'',
						tempid:_book.tempid||'',
						isMdpage:_book.isMdpage,
						version:_book.version||'1.0.0',
						index:'/'+dirname.value
					});
				}
				// if (upload.getAttribute('data-index')==='/404.html'){
				// 	$this.confirm('电子书首页丢失了：[/404.html]！确认提交吗？',subbook);
				// 	return;
				// }
				try{
					if (Object.keys(_book).length>1) {
						console.log(_book)
					};
				}catch(e){
					$this.confirm('电子书配置信息有误！确认提交吗？',subbook);
					return;
				}
				if (!upload.getAttribute('data-book')){
					$this.confirm('电子书配置信息有误！确认提交吗？',subbook);
					return;
				}
				subbook();
			}
		});


	}
	getToken(bkInfo){
		let $this=this;
		Layer({
			width:380,
			height:240,
			title:'验证权限',
			content:`
				<p class="utext ease3">输入当前用户密码</p>	
				<input type="password" maxlength=15 class="upswd inpt ease3" value="" />
				<div class="itoken"><input type="text" class="utoken inpt upswd" id="biao1" style="width:210px;" /><span class="copy">复制</span></div>
			`,
			onShow(){
				$$('.upswd').focus();
				var utoken = $$('.utoken');
				var copy = $$('.copy');
				copy.onclick = function(){
					copyUrl2()
					this.innerHTML = '已复制'
					utoken.blur()
				}
				utoken.onfocus = function() {
					this.select()
				}
			},
			onOK(){
				var upswd=$$('.upswd');
				var itoken=$$('.itoken');
				if (!upswd.value) {
					upswd.focus();
					return
				}
				
				if (~itoken.className.indexOf('itemin')) {
					copyUrl2()
					this.delete();
					return
				}
				$this.props.getUploadToken({
					name: $this.props.user.name,
					pswd: upswd.value,
					bkInfo: JSON.stringify(bkInfo)
				});
				// user:this.props.user.name,
			}
		});
		// API.getToken(pars);
		// 根据pars重新sign一个token
	}
	upload(pars){
		var fd = new FormData();
		var file = document.querySelector('#upload').files[0];
		var type = file.name.replace(/.+?\.(\w+)$/,'$1');
		if (type!='zip') {
			this.showErr('请上传zip类型附件！');
			return;
		}
		fd.append("fileupload", file);
		this.xhr = new XMLHttpRequest();
		var progress=document.querySelector('.progress');
		var filename=document.querySelector('.filename');
		var progressbar=document.querySelector('.progressbar');
		var yes=document.querySelector('.icon-yes');
		var useconf=document.querySelector('.useconf');
		var infoTip=document.querySelector('.filetype-info1');
		let upload=document.querySelector('#upload');
		filename.innerHTML=file.name;
		upload.setAttribute('data-uploading',0);
		progressbar.style.width=0;
		progress.className='progress';
		yes.style.display='none';
		progress.style.display='block';
		progress.className+=' progress-act';
		setTimeout(()=>{
			upload.setAttribute('data-uploading',1);
			var params = pars?('&vs='+pars.vs+'&v='+pars.v):'';
			this.xhr.open("POST", '/api/book/upload?user='+this.props.user.name+'&md='+upload.getAttribute('data-md')+params);
			this.xhr.upload.onprogress = function (event) {
			    if (event.lengthComputable) {
			    	var w=Math.min(213,Math.ceil(213*(event.loaded/event.total)));
			        progressbar.style.width=w+'px';
			        if (w>=213) {
			        	yes.style.display='block';
						useconf.style.display='inline-block';
						infoTip.style.display='inline-block';
			        }
			    }
			};
			this.xhr.onreadystatechange=()=>{
				if (this.xhr.readyState===4 && this.xhr.status===200)
			    {
			    	var res=JSON.parse(this.xhr.responseText);
			    	upload.setAttribute('data-uploading',0);
			    	this.posting=false;
			    	if (res.success) {
						// upload.setAttribute('data-index',res.result.index);
						upload.setAttribute('data-book',base64.encode(encodeURIComponent(JSON.stringify(res.result.book))));
			    	}else{
			    		upload.setAttribute('data-res',res.result);
			    		alert(res.result)
			    	}
			    }
			}
			this.xhr.send(fd);
		},200);
	}
	removeBook(id,_name,parentId,version){
		let $this=this;
		Layer({
			width:350,
			height:200,
			content:'<div style="line-height: 80px;font-size: 14px;color: #666;text-align: center;">确认删除吗？</div>',
			onOK(){
				$this.props.RemoveBook({id,_name,userId: $this.props.user.id, parentId, version});
				setTimeout(()=>{this.delete()},200);
			}
		});
	}
	render(){
		let {books, selectVersion} = this.props;
		books = recombineBooks(books);
		console.log(books)
		return (
			<div className="index">
				<div className="pagectrl">
					<div className="fr btn btn-primary ease3" onClick={()=>this.showLayer()}><i className="iconfont icon-add"></i>新增电子书</div>
				</div>
				<div className="table">
					<ContentSlideIn>
						<table>
							<thead>
								<tr>
									<th align="center" width={50}>序号</th>
									<th align="center" width={60}>图片</th>
									<th width={170}>标题</th>
									<th width={120}>版本</th>
									<th width={120}>作者</th>
									<th width={150}>时间</th>
									<th width={210}>分类</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								{
									books.length?
									books.map((book,i)=>{
										return (
											<SlideInTr key={book.id} item={book}>
												<td align="center">{i+1}</td>
												<td align="center">{book.logo?<img src={book.logo} alt="" width={30} height={24} />:<i className="iconfont icon-book"></i>}</td>
												<td>{book.name}</td>
												<td>
													{book.versions&&book.versions.length?
													<select defaultValue={book.version} className="select-inline" 
														onChange = { 
															e => {
																let tar = e.currentTarget;
																let version = tar.options[tar.selectedIndex].value;
																selectVersion({
																	parentId: book.parentId,
																	version
																});
															}
														}>
														{
															book.versions.map((v,i)=><option key={i} value={v}>{v}</option>)
														}
													</select>:null
													}
												</td>
												<td>{book.author}</td>
												<td>{book.time}</td>
												<td align="center">{book.typesName}</td>
												<td style={{paddingLeft:50}}>
													<a className="item-ctrl ease3" href={book.index?(book.isMdpage==='1'?book.index+('/'+book.version):book.index):'404.html'} target="_blank">打开</a>
													<span className="item-ctrl ease3" onClick={()=>this.showLayer(book.id,book)}>编辑</span>
													<span className="item-ctrl ease3" onClick={()=>this.removeBook(book.id,book.dirname||'',book.parentId||'',book.version||'1.0.0')}>删除</span>
													<span className="item-ctrl ease3" 
														onClick={()=>this.getToken({
															vs:(book.versions||['1.0.0']).join(','),
															v:book.version||'1.0.0',
															user:this.props.user.name||'',
															md:book.isMdpage||'0',
															parentId:book.parentId||'',
															id:book.id,
															bookDir:book.bookDir
														})}>获取Token</span>
												</td>
											</SlideInTr>
										);
									}):
									<tr><td colSpan={8}><div className="nodata">暂无数据</div></td></tr>
								}
							</tbody>
						</table>
					</ContentSlideIn>	
				</div>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return {
		books: state.Books.books,
		types: state.Types.types.reverse()
	}
}
function mapDispatchToProps(dispatch){
	return {
		BooksList: data => dispatch(getBooks(data)),
		TypesList: data => dispatch(getTypes(data)),
		AddBook: data => dispatch(SGaddBook(data)),
		RemoveBook: data => dispatch(SGremoveBook(data)),
		IsExistsDirname: data => dispatch(SGisExistsDirname(data)),
		selectVersion: data => dispatch(selectVersion(data)),
		getUploadToken: data => dispatch(SGgetUploadToken(data))
	}
}